<?php

namespace app\system\controller\order;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Numeral;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class OrderList extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['corp_name_cn', 'corp_name_ko', 'manager'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\order\OrderList;
    }



    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $this->withJoinTable = ['product' => function($query){
            $query->leftJoin(['category']);
        }];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->with(['product' => function($query){
                $query->with(['category'])->order('id asc');
            }])
            ->alias($alias)
            ->where($where);

        $res = db::name('order_l')->alias('l')
            ->field('l.id, l.sale_currency, l.sale_price, l.cost_currency, l.cost_price, l.quantity, p.code_customer, c.name_cn category_name, c.id category_id')
            ->leftJoin('product p', 'p.id=l.product_id')
            ->leftJoin('product_category c', 'c.id=p.category_id');



        if(!empty($param['order_id'])){
            $res = $res->where(['l.order_c_id' => $param['order_id']]);
        }
//        print_r($param);die;
        if(!empty($param['order_s_id'])){
            $res = $res->where(['l.order_s_id' => $param['order_s_id']]);
        }


//        $res = $res->order('id asc')->paginate($limit);
//        $res = $res->order('category.id asc')->paginate($limit);
        $list = $res->order('category_id asc, id asc')->select();
//        $res = $res->paginate($limit);

//        $list = $res->items();


        foreach($list as $key => $val){
            $list[$key]['sale_price'] = $val['sale_currency'] . ' ' . ($val['sale_price'] / $this->multiply);
            $list[$key]['cost_price'] = $val['cost_currency'] . ' ' . $val['cost_price'] / $this->multiply;
            $list[$key]['quantity'] = number_format($val['quantity'] / $this->multiply);
        }


        $this->success('', [
            'list' => $list,
            'total' => count($list),
            'remark' => get_route_remark(),
        ]);
    }


    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(empty($data['product_id'])) $this->error(__('请选择产品'));







            $data['sale_price'] = empty($data['sale_price']) ? 0 : $data['sale_price'] * $this->multiply;
            $data['cost_price'] = empty($data['cost_price']) ? 0 : $data['cost_price'] * $this->multiply;
            $data['quantity'] = empty($data['quantity']) ? 0 : $data['quantity'] * $this->multiply;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $order_c = db::name('order_c')->where(['id' => $data['order_c_id']])->find();
                $order_s = db::name('order_s')->where(['c_id' => $data['order_c_id']])->find();
                $product = db::name('product')->where(['id' => $data['product_id']])->find();
                $category = db::name('product_category')->where(['id' => $product['category_id']])->find();
                if($order_s){ // 添加工厂订单
                    $order_s_id = $order_s['id'];
                }else{
                    $s_insert = [
                        'supplier_id' => $category['supplier_id'],
                        'c_id' => $data['order_c_id'],
                        'create_time' => $order_c['create_time'],
                    ];
                    $order_s_id = db::name('order_s')->insertGetId($s_insert);
                }
                $where = [
                    'order_c_id' => $data['order_c_id'],
                    'product_id' => $data['product_id']
                ];
                $detail = db::name('order_l')->where($where)->find();
                if($detail) $this->error(__('请勿重复添加产品'));

                $data['order_s_id'] = $order_s_id;

//                print_r($data);die;

                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            if(empty($data['product_id'])) $this->error(__('请选择产品'));
            $data['sale_price'] = empty($data['sale_price']) ? 0 : $data['sale_price'] * $this->multiply;
            $data['cost_price'] = empty($data['cost_price']) ? 0 : $data['cost_price'] * $this->multiply;
            $data['quantity'] = empty($data['quantity']) ? 0 : $data['quantity'] * $this->multiply;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $row['cost_price'] /= $this->multiply;
        $row['sale_price'] /= $this->multiply;
        $row['quantity'] /= $this->multiply;

        $product = db::name('product')->where(['id' => $row['product_id']])->find();
        $row['category_id'] = $product['category_id'];

        $this->success('', [
            'row' => $row
        ]);
    }



























}